package controllers;

import java.util.Date;

import models.User;
import helper.CaptchaHelp;
import helper.Cookie;
import helper.RedirectHelp;
import play.data.validation.*;
import play.libs.Codec;
import play.libs.Crypto;
import play.mvc.Controller;
import play.mvc.Http;

/***
 * 
 * @author eliotLiu
 *
 */
public class GateKeeper extends Controller {
	
	static final String NEED_NAME = "请输入用户名";
	static final String NEED_PASSWORD = "请输入密码";
	static final String NEED_EMAIL = "请输入正确的邮箱地址";
	static final String CAPTCHA_ERROR = "验证码错误，请重新输入";
	static final String LOGIN_ERROR = "用户名或者密码错误";	
	static final String USERNAME_DUPLICATE = "用户名已被占用，请重新输入";	

	static final String craneCookieName = "craneKey";
	
	public static User checkLogin() 
	{
		Http.Cookie craneCopkie = request.cookies.get(craneCookieName);
		if (craneCopkie == null) {
			response.removeCookie(craneCookieName);
			login();
		}
		Cookie cookie = Cookie.decode(craneCopkie.value);
		if (cookie == null || !request.remoteAddress.equals(cookie.ip)) {
			response.removeCookie(craneCookieName);
			login();
		}
		User user = User.findById(Long.valueOf(cookie.uuid));
		if(null == user){
			response.removeCookie(craneCookieName);
			login();
		}
		return user;
	}
	
	public static User checkUser()
	{
		Http.Cookie craneCopkie = request.cookies.get(craneCookieName);
		if (craneCopkie == null) {
			return null;
		}
		Cookie cookie = Cookie.decode(craneCopkie.value);
		if (cookie == null || !request.remoteAddress.equals(cookie.ip)) {
			return null;
		}
		return User.findById(Long.valueOf(cookie.uuid));
	}
	
	public static void login()
	{
		Http.Cookie craneCookie = request.cookies.get(craneCookieName);
		if (craneCookie != null) {
			Cookie cookie = Cookie.decode(craneCookie.value);
			if (cookie != null) {
				Application.index();
			}
		}
		String captchaID = CaptchaHelp.generaterCaptchaId();
		render(captchaID);
	}
	
	public static void logout()
	{
		response.removeCookie(craneCookieName);
		Application.index();
	}	
	
	public static void register()
	{
		render();
	}
	
	public static void doLogin(
			@Required(message=NEED_NAME)String username,
			@Required(message=NEED_PASSWORD)String password,
			@Required(message=CAPTCHA_ERROR)String code,
			@Required String captchaID,
			boolean rememberMe)
	{
		//验证参数
		validation.isTrue(CaptchaHelp.check(captchaID, code)).message("验证码错误");
		
		User user = User.connect(username, password);	
		if (null == user || validation.hasErrors()) {
			validation.isTrue(false).message(LOGIN_ERROR);
			validation.keep();
			login();			
		}

		//登录成功
		Cookie cookie = new Cookie(request.remoteAddress,
									user.id+"",
									String.valueOf(new Date().getTime()),
									"");
		if (rememberMe) {
			response.setCookie(craneCookieName, cookie.encode(), "14d");
		} else {
			// cookie valid until the browser close.
			response.setCookie(craneCookieName, cookie.encode());
		}
		String redirectPath = RedirectHelp.getRedirectPath(request);
		if(redirectPath == null || "".equals(redirectPath)){
			Application.index();
		}
		else {
			redirect(redirectPath);
		}
		
	}
	
	public static void captcha(String id) 
	{	    
	    renderBinary(CaptchaHelp.captcha(id,120,40));
	}
	
	public static void captchaIdGenerater()
	{
		renderText(CaptchaHelp.generaterCaptchaId());
	}
	
	
	
	public static void addUser(
			@Required(message=NEED_NAME)String userName,
			@Required(message=NEED_PASSWORD)String password,
			@Email@Required(message=NEED_EMAIL)String emailAddr)
	{
		User user = User.findUser(userName);	
		if (null != user || validation.hasErrors()) {
			validation.isTrue(false).message(USERNAME_DUPLICATE);
			validation.keep();
			register();			
		}



		User newuser=new User(userName, password, emailAddr);
		newuser.save();
		Cookie cookie = new Cookie(request.remoteAddress,newuser.id+"",String.valueOf(new Date().getTime()),"");
		response.setCookie(craneCookieName, cookie.encode());
		Application.index();
	} 
}